<?php
namespace Budget\BudgetBundle\Services;

use Doctrine\ORM\EntityManager;
use Budget\BudgetBundle\Entity\FamilyMonth;
use Budget\BudgetBundle\Helper\DateHelper;

class Statistic
{
    protected $entityManager;
    
    public function __construct(EntityManager $entityManager) 
    {
        $this->entityManager = $entityManager;
    }
    
    public function generateStatistics(FamilyMonth $familyMonth = null)
    {
        if (is_null($familyMonth)) {
            //order of the items on the chart
            return array(
                'totalSaved'      => 0,
                'totalAmountLeft' => 0,
                'saldo'           => 0,
                'totalIncome'     => 0,
                'totalExpenses'   => 0,
                'amountLeft'      => 0,
            );
        }
        //count total income
        $totalIncome = $this->entityManager
                            ->getRepository('BudgetBudgetBundle:Income')
                            ->getTotalSumForMonth($familyMonth);
        
        //getAmount Left from previous month
        $familyMonthPrev = $this->entityManager
                            ->getRepository('BudgetBudgetBundle:FamilyMonth')
                            ->findPrevious($familyMonth);
        $amountLeft = is_null($familyMonthPrev) ? 0 : $familyMonthPrev->getAmountLeft();
        
        $result = array(
            'totalSaved'    => $this->getExpensesSumForFamilyMonth($familyMonth, true),
            'totalExpenses' => $this->getExpensesSumForFamilyMonth($familyMonth),
            'saldo'         => $totalIncome + $amountLeft,
            'totalIncome'   => $totalIncome,
            'amountLeft'    => $amountLeft,
        );
        
        $result['totalAmountLeft'] = $result['saldo'] - $result['totalSaved'] - $result['totalExpenses'];
                
        return $result;
    }
    
    public function getExpensesSumForFamilyMonth(FamilyMonth $familyMonth, $countSavingCategories = false)
    {
        return $this->entityManager
                ->getRepository('BudgetBudgetBundle:Expense')
                ->getExpensesSumForFamilyMonth($familyMonth, $countSavingCategories);       
    }
    
    public function getTotalIncomeByMonth(FamilyMonth $familyMonth)
    {
        return $this->entityManager->getRepository('BudgetBudgetBundle:Income')
                    ->getTotalSumForMonth($familyMonth);
    }
    
    public function calculateAmountLeft(FamilyMonth $familyMonth = null)
    {
        $statistics  = $this->generateStatistics($familyMonth);
        
        $allExpenses = $statistics['totalExpenses'] + $statistics['totalSaved'];
        $allIncomes  = $statistics['totalIncome'] + $statistics['amountLeft'];
        
        return $allIncomes - $allExpenses;
    }
}
